/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */
package me.linkcn.ydtxl.client.sync;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.linkcn.ydtxl.client.Consts;
import me.linkcn.ydtxl.client.sync.object.Group;
import me.linkcn.ydtxl.client.util.ContactHelper;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Service;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract.Groups;
import android.util.Log;

/**
 * @author icer.He
 *
 */
public class ContactSyncService extends Service {
    private static final Object sSyncAdapterLock = new Object();
    private static ContactSyncAdapter sSyncAdapter = null;

    /*
     * {@inheritDoc}
     */
    @Override
    public void onCreate() {
        synchronized (sSyncAdapterLock) {
            if (sSyncAdapter == null) {
                sSyncAdapter = new ContactSyncAdapter(getApplicationContext(), true);
            }
        }
    }

    /*
     * {@inheritDoc}
     */
    @Override
    public IBinder onBind(Intent intent) {
        return sSyncAdapter.getSyncAdapterBinder();
    }
    
    private static class ContactSyncAdapter extends AbstractThreadedSyncAdapter {
    	private static final String TAG = Consts.TAG;
    	private static final Uri CONTENT_URI = Uri.parse(Consts.SERVER_ADDRESS);

        private final AccountManager mAccountManager;
        private final Context mContext;

        public ContactSyncAdapter(Context context, boolean autoInitialize) {
            super(context, autoInitialize);
            mContext = context;
            mAccountManager = AccountManager.get(context);
        }

        @Override
        public void onPerformSync(Account account, Bundle extras, String authority,
            ContentProviderClient provider, SyncResult syncResult) {
        	
        	Log.d(TAG, "onPerformSync");
        	//同步组
        	//取得服务器组列表
    		try {
    			syncGroup();
    	    	
    	    	Log.d(TAG, "zzz");
    	    	
    		} catch (ResourceException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		
        	
        }
        
        private void syncGroup() throws IOException, ResourceException {
        	//同步组
	    	//取得服务器组列表
			Uri groupsUri = Uri.withAppendedPath(CONTENT_URI, "18299063718");
			groupsUri = Uri.withAppendedPath(groupsUri, "groups");
			String groupUriStr = groupsUri.toString();
			String src = new ClientResource(groupUriStr).get().getText();
			ObjectMapper mapper = new ObjectMapper();
			//Group group = mapper.readValue(x, Group.class);
			List<Group> remoteGroupList = mapper.readValue(src, new TypeReference<ArrayList<Group>>(){});
			Map<String, Group> remoteGroupMap = new HashMap<String, Group>();
			for(Group g : remoteGroupList) {
				remoteGroupMap.put(String.valueOf(g.get_id()), g);
			}
			//取得本地组列表
			Map<String, Group> localGroupMap = new HashMap<String, Group>();
			Cursor cursor = mContext.getContentResolver().query(Groups.CONTENT_URI,null,null,null,null);
	    	for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {  
	    		Group g = ContactHelper.getGroup(cursor);
	    		localGroupMap.put(String.valueOf(g.get_id()), g);
	    	}
        }

    }
}
